﻿using System;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;

namespace SIEMENS
{
    public partial class frmMain : Form
    {
        /// 浏览器
        /// </summary>
        public ChromiumWebBrowser chromeBrowser;

        public frmMain()
        {
            InitializeComponent();
            Init();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            var settings = new CefSettings();
            settings.Locale = "zh-CN";
            Cef.Initialize(settings);
            var browserSettings = new BrowserSettings();
            chromeBrowser = new ChromiumWebBrowser("http://localhost:8080");
            chromeBrowser.BrowserSettings = browserSettings;
            chromeBrowser.Dock = DockStyle.Fill;
            this.Controls.Add(chromeBrowser);
            CefSharpSettings.WcfEnabled = true;
            chromeBrowser.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
            var winform = new WinformScript(chromeBrowser, this, new PlcCommunicator());
            winform.InitPLC();
            chromeBrowser.JavascriptObjectRepository.Register("winform", winform, isAsync: false, options: BindingOptions.DefaultBinder);
        }

        protected override void OnLoad(EventArgs e)
        {
            // 获取主屏幕的工作区域（排除任务栏的区域）
            Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;
            // 设置窗体最大化时的边界为工作区域
            this.MaximizedBounds = workingArea;
            this.Size = workingArea.Size; // 设置窗体大小为工作区域大小
            this.Location = Point.Empty;
            base.OnLoad(e);
        }
    }

    /// <summary>
    /// 窗体脚本
    /// </summary>
    public class WinformScript
    {
        private PlcCommunicator plcCommunicator;
        private ChromiumWebBrowser webBrowser;
        private PLCMethods pLCMethods;
        private Form form;

        public WinformScript(ChromiumWebBrowser webBrowser, Form form, PlcCommunicator plcCommunicator)
        {
            this.webBrowser = webBrowser;
            this.form = form;
            this.plcCommunicator = plcCommunicator;
            this.pLCMethods = new PLCMethods(plcCommunicator);
        }

        /// <summary>
        /// 用form执行
        /// </summary>
        /// <param name="action">要执行的方法</param>
        private void FormInvoke(Action action)
        {
            form.Invoke(new Action(action));
        }

        /// <summary>
        /// 关闭窗体
        /// </summary>
        public void CloseForm()
        {
            FormInvoke(() =>
            {
                Application.Exit();
            });
        }

        /// <summary>
        /// 最小化
        /// </summary>
        public void Minimize()
        {
            FormInvoke(() =>
            {
                form.WindowState = FormWindowState.Minimized;
            });
        }

        /// <summary>
        /// 打开开发者工具
        /// </summary>
        public void OpenDev()
        {
            webBrowser.ShowDevTools();
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="controlVoltage"></param>
        /// <param name="motorVoltage"></param>
        /// <param name="v1"></param>
        /// <param name="v2"></param>
        /// <param name="v3"></param>
        /// <param name="v4"></param>
        /// <param name="type"></param>
        /// <param name="secondCoil"></param>
        /// <param name="phase"></param>
        /// <param name="operation"></param>
        /// <returns></returns>
        public string PowerOn(string controlVoltage, string motorVoltage, ushort dcV1, ushort acV, ushort acRate, ushort dcV2, string type, bool secondCoil, string phase, string operation)
        {
            var phases = phase.Split(new char[] { ',' });
            var op = operation[0];
            //先根据哪厢电获取状态
            foreach (var p in phase)
            {
                var result = p == 'A' ? pLCMethods.ReadPhaseAContactStatus() : p == 'B' ? pLCMethods.ReadPhaseBContactStatus() : pLCMethods.ReadPhaseCContactStatus();
                if (null == result)
                    return $"{p}厢触点状态获取失败";
                if (op == 'C' && result == 0)
                    return $"{p}厢触点状态已是合闸状态";
                if (op == 'O' && result == 1)
                    return $"{p}厢触点状态已是分闸状态";
            }
            foreach (var p in phase)
            {
                ushort? result = null;
                if (p == 'A')
                    result = op == 'C' ? pLCMethods.ReadPhaseACloseStatus() : pLCMethods.ReadPhaseAOpenStatus();
                else if (p == 'B')
                    result = op == 'C' ? pLCMethods.ReadPhaseBCloseStatus() : pLCMethods.ReadPhaseBOpenStatus();
                else
                    result = op == 'C' ? pLCMethods.ReadPhaseCCloseStatus() : pLCMethods.ReadPhaseCOpenStatus();
                if (null == result)
                    return $"{p}厢触点状态获取失败";
                if (result == 1)
                    return $"{p}厢触点状态已是{(op == 'C' ? "合闸" : "分闸")}状态";
            }
            //设置选择什么点
            if (!pLCMethods.SelectDCPower(controlVoltage == "DC") || !pLCMethods.SelectACPower(controlVoltage == "AC") || !pLCMethods.SelectExternalPower(controlVoltage == "External Voltage")
                  || !pLCMethods.SelectDCMotorPower(motorVoltage == "DC") || !pLCMethods.SelectACMotorPower(motorVoltage == "AC") || !pLCMethods.SelectExternalMotorPower(motorVoltage == "External Voltage"))
                return "电流类型设置失败";
            //设置电压值
            if (!pLCMethods.WriteDC(dcV1) || !pLCMethods.WriteAC(acV) || !pLCMethods.WriteACRate(acRate) || !pLCMethods.WriteDCVoltage(dcV2))
                return "电流设置失败";
            //选择哪厢电
            if (!pLCMethods.SelectPhaseA(operation == "A") || !pLCMethods.SelectPhaseB(operation == "B") || !pLCMethods.SelectPhaseC(operation == "C") || !pLCMethods.SelectAllPhases(operation == "ABC"))
                return "厢电设置失败";
            //第二线圈
            if (!pLCMethods.SelectSecondaryCoil(secondCoil))
                return "第二线圈设置失败";
            //打开电源
            Thread.Sleep(100);
            if (!pLCMethods.PowerCommand(true))
                return "控制电源打开失败";
            return "";
        }

        /// <summary>
        /// 初始化PLC
        /// </summary>
        public void InitPLC()
        {
            Task.Run(() =>
            {
                //将所有的全部置为false
                pLCMethods.SelectDCPower(false);
                pLCMethods.SelectACPower(false);
                pLCMethods.SelectExternalPower(false);
                pLCMethods.SelectDCMotorPower(false);
                pLCMethods.SelectACMotorPower(false);
                pLCMethods.SelectExternalMotorPower(false);
                pLCMethods.PowerCommand(false);
                pLCMethods.MotorCommand(false);
                pLCMethods.SelectPhaseA(false);
                pLCMethods.SelectPhaseB(false);
                pLCMethods.SelectPhaseC(false);
                pLCMethods.SelectAllPhases(false);
                pLCMethods.SelectSecondaryCoil(false);
                pLCMethods.CloseCommand(false);
                pLCMethods.OpenCommand(false);
                pLCMethods.CloseOpenCommand(false);
                pLCMethods.OpenCloseCommand(false);
                pLCMethods.OpenCloseOpenCommand(false);
                plcCommunicator.Disconnect();
            });
        }
    }
}
